package cn.demo.mq.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 测试1 生产者  工作队列
 * @author Mr.Still
 * @version 1.0.0
 * @date 2021-10-18 14:45
 **/
public class Send {

    public static String QUEUE_NAME = "hello_queue";
    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("8.129.129.84");
            factory.setPort(5672);
            factory.setVirtualHost("/demo");
            factory.setUsername("user");
            factory.setPassword("password");
            //创建连接对象
            connection = factory.newConnection();

            //创建通道
            channel = connection.createChannel();

            //创建队列
            /*
            参数1：队列名称
            参数2：是否持久化
            参数3：是否排他队列
                  如果为true 仅当前队列可见，其他队列不可见 连接断开队列删除
            参数4：是否自动删除
            参数5：自定义参数
             */
            channel.queueDeclare(QUEUE_NAME,false,false,false,null);
            //消息发送
            String msg = "hello,mq";
            //交换机，路由器，自定义参数，消息
            channel.basicPublish("",QUEUE_NAME,null,msg.getBytes("utf-8"));
            System.out.println("消息发送成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally {
            if (null!=channel && channel.isOpen()){
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            if (null!=connection&&connection.isOpen()){
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}











